package com.study.wechatboot.autoreply.service.impl;

import com.study.wechatboot.autoreply.pojo.recvmsg.RecvMsgJson;
import com.study.wechatboot.autoreply.service.AutoReplyService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class AutoReplyServiceImpl implements AutoReplyService {

    private static final Logger logger = LoggerFactory.getLogger(AutoReplyServiceImpl.class);

    @Override
    public void autoReply(RecvMsgJson recvMsgJson) {
        int fromType = recvMsgJson.getData().getData().getFromType();
        int msgSource = recvMsgJson.getData().getData().getMsgSource();
        String fromWxid = recvMsgJson.getData().getData().getFromWxid();
        String autoReplyCont = "你好，我是自动回复机器人，请留言";
        String sendTextUrl = """
                http://127.0.0.1:7777/qianxun/httpapi""";
        String bodyJson = "{\r\n    \"type\": \"sendText\",\r\n    \"data\": {\r\n        \"wxid\": \"" + fromWxid + "\",\r\n        \"msg\": \""+ autoReplyCont +"\"\r\n    }\r\n}";

        // System.out.println(fromType);

        if (fromType == 1 && msgSource == 0) {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
            RequestBody requestBody = RequestBody.create(bodyJson, mediaType);
            Request request = new Request.Builder()
                    .url(sendTextUrl)
                    .method("POST", requestBody)
                    .addHeader("wxid", "wxid_v7nsfafx601q22")
                    .addHeader("safekey", "")
                    .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                    .addHeader("Content-Type", "application/json")
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        System.out.println(response.body().string());
                        System.out.println("自动回复成功");
                    } else {
                        System.out.println("自动回复失败");
                    }
                }
            } catch (Exception e) {
                logger.error("自动回复失败", e);
            }
        }
    }
}
